import {Component, OnInit, ViewChild} from '@angular/core';
import {adSystemApiUrl} from '../../../../config/api';
import {HttpService} from '../../../lib/service/http.service';
import {ModalDirective} from 'ngx-bootstrap';
import {Router} from '@angular/router';

@Component({
  selector: 'app-template',
  templateUrl: './template.component.html',
  styleUrls: ['./template.component.scss']
})
export class TemplateComponent implements OnInit {

  type: string;
  message: string;
  isShow = false;
  totalItems: number;
  itemsPerPage = 12;
  currentPage = 1;
  searchData: string;
  tableData = [];
  operateId: number;

  @ViewChild('deleteModal') public deleteModal: ModalDirective;

  constructor(private httpService: HttpService, private router: Router) {
  }

  ngOnInit() {
    this.getTempList(1);
  }

  // 获取模板列表
  getTempList(page: number, name?: string) {
    let url;
    if (!!name) {
      url = `${adSystemApiUrl}/v1/admin/template_applet/list?page=${page}&pageSize=${this.itemsPerPage}&name=${name}`;
    } else {
      url = `${adSystemApiUrl}/v1/admin/template_applet/list?page=${page}&pageSize=${this.itemsPerPage}`;
    }
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        this.tableData = res.data.data;
      }
    );
  }

  search() {
    this.getTempList(1, this.searchData);
  }

  reset() {
    this.searchData = null;
    this.getTempList(1);
  }

  // 删除弹框
  delTemp(id: number) {
    this.operateId = id;
    this.deleteModal.show();
  }

  delTempSubmit() {
    const url = `${adSystemApiUrl}/v1/admin/template_applet/${this.operateId}/del`;
    return this.httpService.httpPostAuth(url, '').subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '删除成功';
          this.isShow = true;
          this.deleteModal.hide();
          this.getTempList(1);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  edit(id: number) {
    this.router.navigate(['/template/template/eidtTemp/' + id])
  }

  pageChanged(event: any): void {
    window.scrollTo(0,0);
    this.getTempList(event.page, this.searchData);
  }

  promptIsShow(event: any): void {
    this.isShow = event;
  }
}
